package com.uinnova.product.eam.workable.rsm;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

@Component
@Slf4j
public class RsmInterceptor implements HandlerInterceptor {


    @Autowired
    private RsmUtils rsmUtils;

    @Value("${obs.use}")
    private boolean obsUseFlag;

    @Value("${http.resource.space:}")
    private String urlPath;
    @Value("${obs.rsm.url.prefix:/tarsier-eam/rsm}")
    private String rsmUrlPrefix;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!obsUseFlag){
            return true;
        }
        System.out.println("---------进入rsm请求拦截处理器-----------");
        log.info("---------进入rsm请求拦截处理器-----------");
        String uri = request.getRequestURI();
        log.info("当前请求的地址："+uri);
        if(uri.startsWith(rsmUrlPrefix)){
            log.info("拦截到rms请求，进行转发处理");
            String objectName = rsmUtils.processObjectKey(uri);
            log.info("截取到objectName"+objectName);

            try (InputStream rsmContent = rsmUtils.downloadRsm(objectName)) {
                //通过objectName截取出文件类型
                int type = objectName.lastIndexOf(".");
                int name = objectName.lastIndexOf("/");
                String rsmType = objectName.substring(type + 1);
                String rsmName = objectName.substring(name + 1);

                log.info("获取到文件类型：" + rsmType);
                log.info("获取到文件名称：" + rsmName);

                // 设置响应头信息，告诉浏览器需要下载的文件名
                if ("svg".equals(rsmType)) {
                    response.setContentType("image/svg+xml");
                    response.setHeader("Accept-Ranges", "bytes");
                } else {
                    response.setContentType("application/octet-stream");
                }
                //response.setHeader("Content-Disposition", "attachment;filename="+rsmName);
                try (ServletOutputStream outputStream = response.getOutputStream()) {
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    while ((bytesRead = rsmContent.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                }
            }
            return false;
        }
        return true;
    }

    private String getUrlHost(String path) throws MalformedURLException {

        URL urlObject = new URL(path);
        String host = urlObject.getHost();
        int port = urlObject.getPort();

        if(StringUtils.isNotBlank(host) && port > 0 ){
            return host + ":" + port;
        }else if(StringUtils.isNotBlank(host)) {
            return host;
        }else{
            return "";
        }

    }

}
